package com.fhc.view.utils

import android.annotation.SuppressLint
import android.content.Context
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toolingGraphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil3.ImageLoader
import coil3.compose.AsyncImagePainter
import coil3.compose.AsyncImagePainter.State
import coil3.compose.rememberAsyncImagePainter
import coil3.request.crossfade
import coil3.svg.SvgDecoder

@Composable
fun SvgIcon(
    path: String,
    contentDescription: String?,
    @SuppressLint("ModifierParameter")
    modifier: Modifier = Modifier.size(24.dp)
) {
    IconNoTint(painter = rememberAssetsPainter(path = path), contentDescription, modifier)
}


@Composable
fun SvgFitWidthIcon(
    path: String,
    svgWidth: Dp,
    modifier: Modifier = Modifier
) {
    var svgH by remember { mutableStateOf(0.dp) }
    val painter = rememberAssetsPainter(path = path, onState  = { state ->
        if (state is State.Success) {
            val width = state.result.image.width
            val height = state.result.image.height
            svgH = svgWidth * height / width
        }
    })
    Box(modifier.size(width = svgWidth, height = svgH)){
        Box(
            Modifier.size(svgWidth,svgH ).paint(painter,  contentScale = ContentScale.Fit)
        )
    }
}

@Composable
private fun rememberAssetsPainter(
    path: String,
    imageLoader: ImageLoader = rememberImageLoader(),
    transform: (State) -> State = AsyncImagePainter.DefaultTransform,
    onState: ((State) -> Unit)? = null,
    contentScale: ContentScale = ContentScale.Fit,
    filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,
): AsyncImagePainter {
    return rememberAsyncImagePainter(
        model = "file:///android_asset/${path}",
        imageLoader = imageLoader,
        transform = transform,
        onState = onState,
        contentScale = contentScale,
        filterQuality = filterQuality
    )
}





// Default icon size, for icons with no intrinsic size information
private val DefaultIconSizeModifier = Modifier.size(24.0.dp)
private fun Size.isInfinite() = width.isInfinite() && height.isInfinite()
private fun Modifier.defaultSizeFor(painter: Painter) =
    this.then(
        if (painter.intrinsicSize == Size.Unspecified || painter.intrinsicSize.isInfinite()) {
            DefaultIconSizeModifier
        } else {
            Modifier
        }
    )

@Composable
private fun IconNoTint(
    painter: Painter,
    contentDescription: String?,
    modifier: Modifier = Modifier,
) {
    val semantics =
        if (contentDescription != null) {
            Modifier.semantics {
                this.contentDescription = contentDescription
                this.role = Role.Image
            }
        } else {
            Modifier
        }
    Box(
        modifier
            .toolingGraphicsLayer()
            .defaultSizeFor(painter)
            .paint(painter,  contentScale = ContentScale.Fit)
            .then(semantics)
    )
}


@Composable
fun SvgIconRotate(
    path: String,
    modifier: Modifier = Modifier.size(24.dp),
    tint: Color = LocalContentColor.current
) {
    val infiniteTransition = rememberInfiniteTransition()
    val angle = infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(1500, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    )
    Icon(painter = rememberAssetsPainter(path = path), null, modifier.rotate(angle.value), tint)
}

//
//// 创建一个加载SVG的函数
//@Composable
//fun AssetSvgImage(
//    path: String, // SVG图片的URL或文件路径
//    modifier: Modifier = Modifier,
//) {
//
//    val painter = rememberAsyncImagePainter(
//        model = "file:///android_asset/${path}",
//        imageLoader = ImageLoader.Builder(LocalContext.current).components {
//            add(SvgDecoder.Factory())
//        }.crossfade(true).build()
//    )
//    Image(
//        painter = painter,
//        contentDescription = null,
//        modifier = modifier
//    )
//}

@Composable
private fun rememberImageLoader(context: Context = LocalContext.current): ImageLoader {
    val loader = remember {
        ImageLoader.Builder(context)
            .components {
                add(SvgDecoder.Factory())
            }.crossfade(true)
//            .memoryCache {
//                MemoryCache.Builder(context)
//                    .maxSizePercent(0.25)
//                    .build()
//            }
//            .diskCache {
//                DiskCache.Builder()
//                    .directory(context.cacheDir.resolve("image_cache"))
//                    .maxSizePercent(0.02)
//                    .build()
//            }
            .build()
    }
    return loader

}